/*
 * @Author: Cathy
 * @Date: 2021-07-05 11:12:00
 * @LastEditors: Cathy
 * @LastEditTime: 2021-07-05 14:30:19
 * @Description: axios拦截器
 */
import axios from 'axios'
import { Message } from 'element-ui'
// import store from '@/store'

const service = axios.create({
  baseURL: process.env.VUE_APP_API_URL // 请求url
//   withCredentials: false  // 在跨域请求时发送cookie
//   timeout: 30000  // 请求超时时间(单位：毫秒)
})

const pendingRequests = new Map()

service.clearRequestList = () => {
  pendingRequests.clear()
}

// 请求拦截
service.interceptors.request.use(config => {
  const requestKey = `${config.url}/${JSON.stringify(config.params)}/${JSON.stringify(config.data)}&request_type=${config.method}`
  if (pendingRequests.has(requestKey)) {
    config.cancelToken = new axios.CancelToken(cancel => {
      // cancel 函数的参数会作为 promise 的 error 被捕获
      cancel(`重复请求：${requestKey}`)
    })
  } else {
    pendingRequests.set(requestKey, config)
    config.requestKey = requestKey
  }
  return config
},
error => {
  // 这里出现错误可能是网络波动造成的，清空 pendingRequests 对象
  pendingRequests.clear()
  console.error(error)
  Message.error(error)
  return Promise.reject(error)
})

// 响应拦截
service.interceptors.response.use(response => {
  pendingRequests.delete(response.config.requestKey)
  const res = response.data
  return res
},
error => {
  if (axios.isCancel(error)) {
    console.warn(error)
  } else {
    Message.error(error)
    pendingRequests.clear()
    console.error(error)
  }
  return Promise.reject(error)
})

export default service
